﻿using HXH.Serialization.Abstractions;
using Newtonsoft.Json;
using System;
using System.Text;
using System.Threading.Tasks;

namespace HXH.Serialization.Json
{
    /// <summary>
    /// Json 序列化消息
    /// </summary>
    public class JsonMessageSerializer : IMessageSerializer
    {
        /// <summary>
        /// 序列化消息
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="message"></param>
        /// <returns></returns>
        public byte[] SerializerBytes<T>(T message)
        {
            return Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message));
        }
        /// <summary>
        /// 异步序列化消息
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="message"></param>
        /// <returns></returns>
        public Task<byte[]> SerializerBytesAsync<T>(T message)
        {
            return Task.Run(() =>
            {
                return Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message));
            });
        }
        /// <summary>
        /// 反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public T Deserialize<T>(byte[] bytes)
        {
            return JsonConvert.DeserializeObject<T>(Encoding.UTF8.GetString(bytes));
        }
        /// <summary>
        /// 异步反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public Task<T> DeserializeAsync<T>(byte[] bytes)
        {
            return Task.Run(() =>
            {
                return JsonConvert.DeserializeObject<T>(Encoding.UTF8.GetString(bytes));
            });
        }

    }
}
